package com.wuhao.shootclient.pusher;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wuhao.shootclient.bean.HandShakeBean;
import com.wuhao.shootclient.bean.PulseBean;
import com.wuhao.shootclient.util.LogUtil;
import com.wuhao.shootclient.util.UrlHelper;
import com.wuhao.shootclient.util.eventbus.AppEventBus;
import com.wuhao.shootclient.util.eventbus.EventBusCode;
import com.xuhao.didi.core.iocore.interfaces.IPulseSendable;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.client.sdk.client.connection.NoneReconnect;

import org.json.JSONObject;

import java.nio.charset.Charset;
import java.util.Arrays;

public class SocketService extends Service {

    private ConnectionInfo mInfo;
    private IConnectionManager mSocketManager;



    @Override
    public void onCreate() {
        Log.i("Kathy", "onCreate - Thread ID = " + Thread.currentThread().getId());
        super.onCreate();
        initSocket();
    }


    private void initSocket() {
        //设置socket url
        //连接参数设置(IP,端口号),这也是一个连接的唯一标识,不同连接,该参数中的两个值至少有其一不一样
        mInfo = new ConnectionInfo(UrlHelper.SOCKET, UrlHelper.SOCKET_PORT);
        OkSocketOptions.Builder builder = new OkSocketOptions.Builder();
        //设置心跳
        builder.setPulseFrequency(110 * 1000);
        //调用OkSocket,开启这次连接的通道,拿到通道Manager
        mSocketManager = OkSocket.open(mInfo).option(builder.build());
        //设置回调
        mSocketManager.registerReceiver(adapter);
        //开启重连机制
        if (mSocketManager.getReconnectionManager() instanceof NoneReconnect) {
            mSocketManager.option(new OkSocketOptions.Builder(mSocketManager.getOption()).setReconnectionManager(OkSocketOptions.getDefault().getReconnectionManager()).build());
            LogUtil.error("打开重连管理器(Turn On The Reconnection Manager)");
        }
        //开启 长连接
        mSocketManager.connect();
    }

    private SocketActionAdapter adapter = new SocketActionAdapter() {

        @Override
        public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
            LogUtil.error("连接成功(Connecting Successful)------tip"+info.getIp());

            mSocketManager.send(new HandShakeBean());
            //发送心跳数据
            mSocketManager.getPulseManager().setPulseSendable(new PulseBean());
        }

        @Override
        public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
            if (e != null) {
                if (e instanceof RedirectException) {
                    LogUtil.error("正在重定向连接(Redirect Connecting)...------tip"+info.getIp());
                    mSocketManager.switchConnectionInfo(((RedirectException) e).redirectInfo);
                    mSocketManager.connect();
                } else {
                    LogUtil.error("异常断开(Disconnected with exception):" + e.getMessage()+"------tip"+info.getIp());
                }
            } else {
                LogUtil.error("正常断开(Disconnect Manually)------tip"+info.getIp());
            }

        }

        @Override
        public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
            LogUtil.error("连接失败(Connecting Failed)------tip"+info.getIp());
            LogUtil.error("连接失败(Connecting Failed)------tip"+info.getIp()+"---" + e.toString() + "--" + action);
        }

        @Override
        public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
            String str = new String(data.getBodyBytes(), Charset.forName("gbk"));
            LogUtil.error("最初数据" + str);
            //后台返回数据shootingDataVo.getData().getPeopleName()
            try {
                JSONObject object = new JSONObject(str);
                int code = object.getInt("code");
                AppEventBus.getInstance().post(EventBusCode.EVENT_TYPE,str);
                switch (code) {
                    case 16:
                        //心跳
                        LogUtil.error("收到心跳,喂狗成功(Heartbeat Received,Feed the Dog)------tip"+info.getIp());
                        mSocketManager.getPulseManager().feed();
                        AppEventBus.getInstance().post(EventBusCode.DEBUG_SOCKET,"收到心跳,喂狗成功");
                        break;
                    case 54:
                        //登陆成功
                        String msg = object.getString("msg");
                        LogUtil.error("握手成功! 握手信息(Handshake Success):" + msg + ". 开始心跳(Start Heartbeat)..------tip"+info);
                        AppEventBus.getInstance().post(EventBusCode.DEBUG_SOCKET,"握手成功! 握手信息"+msg);
                        //  SystemTTS.getInstance().playText("握手成功! 握手信息(Handshake Success):" + handshake + ". 开始心跳(Start Heartbeat)..");
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

        @Override
        public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
            //发送数据回调
            byte[] bytes = data.parse();
            bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = JsonParser.parseString(str).getAsJsonObject();
            int code = jsonObject.get("code").getAsInt();
            switch (code) {
                case 54: {
                    String handshake = jsonObject.get("msg").getAsString();
                    LogUtil.error("发送握手数据(Handshake Sending):" + handshake+"------tip"+info.getIp());
                    mSocketManager.getPulseManager().pulse();
                    AppEventBus.getInstance().post(EventBusCode.DEBUG_SOCKET,"发送握手数据"+handshake);
                    break;
                }
                default:
                    LogUtil.error(str);
                    AppEventBus.getInstance().post(EventBusCode.DEBUG_SOCKET,"发送握手数据code不为54"+str);
            }
        }

        @Override
        public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
            byte[] bytes = data.parse();
            bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = JsonParser.parseString(str).getAsJsonObject();
            int code = jsonObject.get("code").getAsInt();
            if (code == 16) {
                LogUtil.error("发送心跳包(Heartbeat Sending)------tip"+info.getIp());
                AppEventBus.getInstance().post(EventBusCode.DEBUG_SOCKET,"发送心跳包");
            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
